import {
	API_URL
} from '@/env'
import {
	initVueI18n
} from '@dcloudio/uni-i18n'
import messages from '@/locale/index'
const {
	t
} = initVueI18n(messages)

/**
 * 公共请求类
 */
class Request {
	constructor() {
		// 请求地址
		this.config.url = API_URL;
		// 请求拦截
		this.requestInterceptors();
	}

	config = {
		url: null,
		header: {
			'content-type': 'application/json',
			'Accept': 'application/json, text/plain, */*',
			'Authorization': uni.getStorageSync('token') || '123'
		},
		method: 'GET',
		dataType: 'json',
		responseType: 'text',
	}

	// 是否验证登录
	isLogin = true;

	// 是否验证错误信息
	isError = true;

	/**
	 * get请求
	 * @param {string} url
	 * @param {object} params
	 */
	async get(url, params = {}) {
		this.config.method = 'GET';
		this.config.data = params;
		return this.request(url);
	}

	/**
	 * post请求
	 * @param {string} url
	 * @param {object} data
	 */
	async post(url, data = {}, header = null) {
		this.config.method = 'POST';
		this.config.data = data;
		if (header) {
			this.config.header = header;
		}
		return this.request(url);
	}

	/**
	 * put请求
	 * @param {string} url
	 * @param {object} data
	 */
	async put(url, data = {}) {
		this.config.method = 'PUT';
		this.config.data = data;
		return this.request(url);
	}

	/**
	 * delete请求
	 * @param {string} url
	 */
	async delete(url) {
		this.config.method = 'DELETE';
		return this.request(url);
	}

	/**
	 * 请求
	 * @param {string} url
	 * @param {object} params
	 */
	async request(url, params = {}) {
		const newConfig = JSON.parse(JSON.stringify(this.config))
		newConfig.url = this.config.url + url;
		return await uni.request(newConfig);
	}

	/**
	 * 拦截
	 */
	async requestInterceptors() {
		let _this = this;
		uni.addInterceptor('request', {
			// 请求前
			async invoke(args) {
				// 验证是否登录
				if (_this.isLogin) {
					let check = await _this.checkLogin();
					if (!check) {
						// 关闭请求
						throw new Error(t('user.logged'))
					}
				}

				// args.data.token = uni.getStorageSync('token');
				args.header.Authorization = uni.getStorageSync('token')

				return args;
			},
			// 请求后
			async success(args) {
				// TODO: 请求后的处理，登录失效等
				if (args.statusCode === 200) {
					if (args.data.code == 4001) { // 去登录
						uni.showToast({
							title: t('please.logfirst'),
							icon: 'none'
						});
						uni.showModal({
							title: t('home.popup-prompt'),
							content: `${t('login.expired')}，${t('please.logfirst')}`,
							cancelText: t('home.btn-cancel'),
							confirmText: t('home.btn-Confirm-appointment'),
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pagesA/login/login'
									});
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					} else if (args.data.code === 500 && _this.isError) {
						console.log('Erro-500==', args.data.message)
						// uni.showToast({
						// 	title: args.data.message,
						// 	icon: 'none'
						// });
					}
				} else {
					uni.showToast({
						title: t('request.failure'),
						icon: 'none'
					});
				}

				return args;
			},
			// 请求失败
			async fail(err) {
				console.log('请求失败==', err)
				uni.showToast({
					title: t('request.failure'),
					icon: 'none'
				});
			},
			// 请求完成
			async complete(res) {
				// console.log('interceptor-complete')
			}
		});
	}

	/**
	 * 验证登录
	 */
	async checkLogin() {
		const token = uni.getStorageSync('token');
		const userinfo = uni.getStorageSync('userinfo');
		if (!token || !userinfo.phone) {
			uni.showToast({
				title: t('please.logfirst'),
				icon: 'none'
			});

			// TODO: 跳转登录页等处理
			setTimeout(() => {
				uni.navigateTo({
					url: '/pagesA/login/login'
				});
			}, 1500);

			return false;
		}

		return token;
	}

}

export default new Request();